function varargout = create_label(varargin)

%  __  __                            _   _       
% |  \/  |                          | | | |      
% | \  / | __ _ _ __ __ _ _   _  ___| |_| |_ ___ 
% | |\/| |/ _` | '__/ _` | | | |/ _ \ __| __/ _ \
% | |  | | (_| | | | (_| | |_| |  __/ |_| ||  __/
% |_|  |_|\__,_|_|  \__, |\__,_|\___|\__|\__\___|
%                      | |                       
%                      |_|                       
%  _    _       _                    _ _         
% | |  | |     (_)                  (_) |        
% | |  | |_ __  ___   _____ _ __ ___ _| |_ _   _ 
% | |  | | '_ \| \ \ / / _ \ '__/ __| | __| | | |
% | |__| | | | | |\ V /  __/ |  \__ \ | |_| |_| |
%  \____/|_| |_|_| \_/ \___|_|  |___/_|\__|\__, |
%                                           __/ |
%                                          |___/ 
% 
% Last Modified by Corey Bost for Marquette University's
% Speech and Signal Processing Lab
% This module is used for creating the master label file (MLF). This MLF
% is used later during the recognition process.
%To being, you can click on the "Use Categories" check box if you've set
%those up. Then just highlight the categories you need the label file for,
%(read the ones to be used for training), and then click the create button.
%If you havn't done categories, you can click the browse button and
%navigate to the folder with your data in it instead. Remember, to do this
%in this manner, your data must be divied into folders by sound category.

% This file is part of the Marquette Univeristy Speech Recognition Toolkit.
% Copyright 2009

%CREATE_LABEL M-file for create_label.fig
%      CREATE_LABEL, by itself, creates a new CREATE_LABEL or raises the existing
%      singleton*.
%
%      H = CREATE_LABEL returns the handle to a new CREATE_LABEL or the handle to
%      the existing singleton*.
%
%      CREATE_LABEL('Property','Value',...) creates a new CREATE_LABEL using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to create_label_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      CREATE_LABEL('CALLBACK') and CREATE_LABEL('CALLBACK',hObject,...) call the
%      local function named CALLBACK in CREATE_LABEL.M with the given input
%      arguments.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help_menu create_label

% Last Modified by GUIDE v2.5 30-Jul-2009 12:03:43

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @create_label_OpeningFcn, ...
                   'gui_OutputFcn',  @create_label_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before create_label is made visible.
function create_label_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for create_label
handles.output = hObject;
% main_dir is used to keep track of the main directory of the program
global main_dir; 
if isnumeric(main_dir), main_dir = strrep(which('create_label_OpeningFcn'),'\create_label.m','');end
% Update handles structure
guidata(hObject, handles);
set(gcf,'CloseRequestFcn',@my_closefcn);

% UIWAIT makes create_label wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% User defined close function
function my_closefcn(hObject, eventdata, handles, varargin)
%Close function
global main_dir;
cd(main_dir);
delete(gcf);
htk_tools

% --- Outputs from this function are returned to the command line.
function varargout = create_label_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%This is the browse button. When clicked, the directory chosen is stored
% in Location.
Location = uigetdir();
%If a location was chosen, the file path is displayed in the listbox.
%In addition, the create button is turned to "enabled".
if Location ~= 0
    set(handles.listbox1,'value',1);
    set(handles.listbox1,'string',[]);
    set(handles.listbox1,'string',Location)
    set(handles.create_label,'enable','on');
    set(handles.create_label,'tooltipstring','Click here to create the master label file in the selected location.');
end


% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1


% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
set(hObject,'Max',2);


% --- Executes on button press in create_label.
function create_label_Callback(hObject, eventdata, handles)
% hObject    handle to create_label (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global main_dir;
 global cats_used
Location = get (handles.listbox1, 'string');
use_cats = get(handles.checkbox1,'value');
run_flag = 1;
if ~use_cats
    run_flag = test_for_run(Location);
    cats_used = 0;
else
   cats_used = get(handles.listbox1,'Value');
end

cd([main_dir '/Data']) %This is the data folder for the program

fid=fopen('label.mlf','w+');
fprintf(fid,'#!MLF!#\n');
if ~(use_cats) & run_flag
    file_dir=dir(Location);
    % This for loop extracts the sound types as the folder name
    % in which the file is saved in.
    for i=1:length(file_dir)-2
        calltype{i}=file_dir(i+2).name;
    end
elseif use_cats
    cats = get(handles.listbox1,'string');
    calltype = cats(get(handles.listbox1,'value'));
end

%To show the user progress, as it sometimes take a while.
if run_flag | use_cats
    h = waitbar(0,'Creating label file...');
    number = 0;
    count = 0;
end
%This for loop determines how many files there are in total
%so the wait bar can show accurate progress.
if run_flag | use_cats
    for k=1:length(calltype)
        if ~use_cats & run_flag
            files_eachtype=dir([Location '\' calltype{k} ]);
            number = number + length(files_eachtype);
        elseif exist([main_dir '/Data/Categories/' calltype{k} '.category'],'file')==2 & use_cats
            fidz = fopen([main_dir '/Data/Categories/' calltype{k} '.category']);
            while ~feof(fidz)
                test = textscan(fidz,'%q');
            end
            fclose(fidz);
            files_eachtype = test{1};
            number = number + length(files_eachtype);
        else
            errordlg(['The category "' calltype{k} '" does not have any files '...
                'associated with it. Please use the Create Category module to do '...
                'this, or select a different category.']); delete(h); return;
        end
    end
end
%The outer for loop goes through the folders iteratively
%while the inner for loop goes through the files.
%Each pass adds the file name to the master label file.
if run_flag | use_cats
    for k=1:length(calltype) %Calltype is number of sub folders
        if use_cats
            fidz = fopen([main_dir '/Data/Categories/' calltype{k} '.category']);
            while ~feof(fidz)
                test = textscan(fidz,'%q');
            end
            fclose(fidz);
            files_eachtype = test{1};
            for j=1:length(files_eachtype)
                count = count +1;
                fprintf(fid,['"*/' calltype{k} '_' num2str(j) '.lab" \n']);
                fprintf(fid,'sil \n');
                fprintf(fid,['"' calltype{k} '"\n']);
                fprintf(fid,'sil \n');
                fprintf(fid,'.\n');
                waitbar(count/number,h,['Writing ' calltype{k} ' labels.']);
            end
        elseif ~use_cats & run_flag
            files_eachtype=dir([Location '\' calltype{k} ]);
            for j=1:length(files_eachtype)-2
                count = count +1;
                fprintf(fid,['"*/' calltype{k} '_' num2str(j) '.lab" \n']);
                fprintf(fid,'sil \n');
                fprintf(fid,['"' calltype{k} '"\n']);
                fprintf(fid,'sil \n');
                fprintf(fid,'.\n');
                waitbar(count/number,h,['Writing ' calltype{k} ' labels.']);
            end
        end
    end
end
%Here the wait bar is finally delete, and the pause
%Is so it doesn't happen instantly when the MLF is done.
if run_flag | use_cats
    save([main_dir '/Data/Result_allcalltype/cats_used.mat'],'cats_used');
    waitbar(1,h,'Labels completed!');
    pause(1);
    fclose(fid);
    delete(h);
    cd('..');
end
if ~run_flag
    warndlg(['You have set up your sound directory incorrectly.'...
        'For more information, please read the tutorial.'],'Danger!');
end
    



% --------------------------------------------------------------------
function file_menu_Callback(hObject, eventdata, handles)
% hObject    handle to file_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function help_menu_Callback(hObject, eventdata, handles)
% hObject    handle to help_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function exit_Callback(hObject, eventdata, handles)
% hObject    handle to exit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
my_closefcn(hObject,eventdata,handles)


% --------------------------------------------------------------------
function about_us_Callback(hObject, eventdata, handles)
% hObject    handle to about_us (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
about_us;

% --------------------------------------------------------------------
function help_Callback(hObject, eventdata, handles)
% hObject    handle to help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%{
helpdlg(sprintf(['Use the Browse button to find the directory containing your data.'...
    ' Once you have located the data, select the folder in which'...
    ' all of your subfolders reside.\n\n'...
    'Once your data is selected, simply click the "Create Labels"'...
    ' button and the Master Label File will be created.']));
%}
help_launch('label');

% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global main_dir;
%This checkbox is to use the categories the user set up before hand
%instead of using a directory structure
if get(hObject,'Value')
    fid = fopen([main_dir '/Data/Categories/Master_Cat.category']);
    while ~feof(fid)
        test = textscan(fid,'%q');
    end
    fclose(fid);
    master = test{1};
    set(handles.listbox1,'string',master);
    set(handles.create_label,'enable','on');
else
    set(handles.create_label,'enable','off');
end


% Hint: get(hObject,'Value') returns toggle state of checkbox1
